/**
 * 用户接口路由
 */
const router = require("express").Router()
const service = require("../service").user()
const setCookies = require("../util").setCookies

// 用户登录接口
router.post('/login', async (req, resp) => {
  const username = req.body.username
  const password = req.body.password
  const res = await service.login(username, password)
  if (res === 'fail') {
    resp.send(res)
  }
  // 设置cookie
  setCookies(resp, {
    username,
    role: res.data.role
  })
  resp.send(res)
})

// 用户注销接口
router.get('/token/logout', async (req, resp) => {
  const username = req.cookies.username
  const res = await service.logout(username)
  setCookies(resp, {
    username: undefined,
    role: undefined
  })
  resp.send(res)
})

module.exports = router